package handler

import (
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
	"send-id-num/internal/repository"
	"send-id-num/pkg/http"
	"send-id-num/pkg/logger"
)

type LoginReq struct {
	QQNum    int    `json:"qqNum" binding:"required"`
	Password string `json:"password" binding:"required"`
}

func Login(c *gin.Context) {
	var req LoginReq
	err := c.ShouldBindJSON(&req)
	if err != nil {
		c.JSON(http.StatusOK, http.FailureResDefaultCode(err.Error()))
		return
	}
	// TODO 区分source
	// 校验账号密码
	user, err := repository.GetUserInfoByQQNum(req.QQNum)
	if err == gorm.ErrRecordNotFound || user.Id == 0 {
		c.JSON(http.StatusOK, http.FailureResDefaultCode("未找到该账号信息，请联系管理员！"))
		return
	}
	if err != nil {
		c.JSON(http.StatusOK, http.FailureResDefaultCode("GetUserInfoByQQNum err "+err.Error()))
		return
	}
	if user.Password == "" {
		c.JSON(http.StatusOK, http.FailureResDefaultCode("请先设置密码！"))
		return
	}
	if user.Password != req.Password {
		c.JSON(http.StatusOK, http.FailureResDefaultCode("密码不正确！"))
		return
	}
	// 登录成功生成token
	token, err := http.GenerateUserToken(user.Id, user.Source)
	if err != nil {
		logger.Log.Error("GenerateUserToken err ", err)
		c.JSON(http.StatusOK, http.FailureResDefaultCode("生成token错误！"))
		return
	}

	c.JSON(http.StatusOK, http.SuccessResWithToken(token))
}
